import {
    UserLogin,
    GetPublicKey,
    getUserInfo,
    LogoutAccessToken,
    LogoutRefreshToken,

} from "@/api/modules/user";
import {
    encryptData
} from "@/utils/encrypt";
import {
    getAccessToken,
    setAccessToken,
    getRefreshToken,
    setRefreshToken,
    setPublicKey,
    getPublicKey,
    removeRefreshToken,
    removeAccessToken,
    claimUserInfo,
    setUserInfo,
} from "@/utils/auth";
import {
    resetRouter
} from "@/router";
import qs from "qs";
import {
    Message
} from "element-ui";
const getDefaultState = () => {
    return {
        // 获取token
        accessToken: getAccessToken(),
        refreshToken: getRefreshToken(),
        publicKey: getPublicKey(),
        userInfo: claimUserInfo(), // 用户信息
        departmentId: null
    };
};

const state = getDefaultState();

const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState());
    },
    SET_accessToken: (state, accessToken) => {
        state.accessToken = accessToken;
    },
    SET_NAME: (state, name) => {
        state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar;
    },
    SETTOKEN: (state, accessToken, refreshToken) => {
        state.accessToken = accessToken;
        state.refreshToken = refreshToken;
    },
    SETPUBLICKEY: (state, publicKey) => {
        state.publicKey = publicKey;
    },
    SETUSERINFO: (state, userInfo) => {
        state.userInfo = userInfo
    },
    // 设置部门ID
    SETDEPARTMENTID(state, departmenId) {
        state.departmentId = departmentId
    }
};

const actions = {
    GetUserInfo({
        commit
    }) {
        return new Promise((resolve, reject) => {
            // 获取用户信息
            getUserInfo().then(res => {
                if (res.status == 200) {
                    // 存储用户信息
                    commit("SETUSERINFO", res.data)
                    setUserInfo(res.data)
                    console.log('userInfo', res.data)
                    resolve()
                }
            }).catch(err => {
                reject(err)
            })
        })
    },
    // 用户登录
    login({
        commit
    }, userInfo) {
        const {
            username,
            password
        } = userInfo;
        return new Promise((resolve, reject) => {
            // 密码加密
            console.log(username, password);
            const datas = qs.stringify({
                username: username.trim(),
                password: encryptData(password.trim()),
                type: 'admin'
            });
            UserLogin(datas)
                .then((res) => {
                    console.log(res)
                    if (res.status == 200) {
                        // 存储token
                        commit("SETTOKEN", res.data.AccessToken, res.data.RefreshToken);
                        setAccessToken(res.data.AccessToken);
                        setRefreshToken(res.data.RefreshToken);
                        resolve();
                    } else if (res.status == 422) {
                        Message.error(res.msg);
                        reject(res.msg);
                    } else if (res.status == 403) {
                        reject(res.msg)
                    }
                })
                .catch((error) => {
                    reject(error);
                });
        });
    },
    // user logout
    logout({
        commit,
        state
    }) {
        return new Promise((resolve, reject) => {
            LogoutAccessToken()
                .then(res1 => {
                    console.log(res1)
                    const refreshToken = getRefreshToken()
                    if (res1.status == 200) {
                        LogoutRefreshToken(refreshToken).then(res2 => {
                            console.log(res2)
                            if (res2.status == 200 || res2.status == 401) {
                                // 删除token
                                removeAccessToken();
                                removeRefreshToken();
                                resetRouter();
                                commit("RESET_STATE");
                                resolve();
                            } else {
                                reject(res2.msg)
                            }

                        }).catch((error) => {
                            reject(error);
                        })
                    } else {
                        console.log(res1.msg)
                    }

                })
                .catch((error) => {
                    reject(error);
                });
        });
    },

    // remove token
    resetToken({
        commit
    }) {
        return new Promise((resolve) => {
            removeToken(); // must remove  token  first
            commit("RESET_STATE");
            resolve();
        });
    },
    // 获取公钥
    getPublicKey({
        commit
    }) {
        return new Promise((resolve, reject) => {
            GetPublicKey()
                .then((res) => {
                    console.log(res)
                    if (res.status == 200) {
                        // 存储公钥
                        commit("SETPUBLICKEY", res.data.public_key);
                        setPublicKey(res.data.public_key);
                        resolve();
                    } else {
                        reject(new Error("获取公钥失败"));
                    }
                })
                .catch((err) => reject(err));
        });
    },
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
};